<?php
// echo "
// {
// 	root: [
// 		{ id: 1, text: 'Project A', leaf: false, expandable: false},
// 		{ id: 2, text: 'Project B', leaf: false, expandable: false},
// 		{ id: 3, text: 'Project C', leaf: false, expandable: true,
// 			root: [
// 				{ id: 4, text: 'Folder A', leaf: true},
// 				{ id: 5, text: 'Folder B', leaf: true}
// 			]
// 		},
// 		{ id: 6, text: 'Project D', leaf: false, expandable: false}
// 	]
// }";

session_start();
include_once dirname(__FILE__).'/../../db/rdb/factory/RDBDAOFactory.php';

if(isset($_SESSION['user'])) {
	$user = unserialize($_SESSION['user']);
	$rdbFactory = DAOFactory::getDAOFactory(DAOFactory::$RDB);
	$userJoinProjectDAO = $rdbFactory->getUserJoinProjectDAO();
	$projectFolderDAO = $rdbFactory->getProjectFolderDAO();
	$pros = $userJoinProjectDAO->getProjectByUser($user, UserJoinProject::$ALL_ROLE);
	
// 	$result = 
// 	array('root' => array(
// 							array('id' => 1, 'text' => 'Project A', 'leaf' => 'false', 'expandable' => false),
// 							array('id' => 2, 'text' => 'Project B', 'leaf' => 'false', 'expandable' => true,
// 									'root' => array(
// 															array('id' => 1, 'text' => 'Project A', 'leaf' => false, 'expandable' => false),
// 															array('id' => 2, 'text' => 'Project B', 'leaf' => false, 'expandable' => false)
// 													)
									
// 							)
// 					)				
// 	);
	
	foreach ($pros as $pro) {
		$projectList = array('id' => 'p_'.$pro->getProjectPK(), 'text' => $pro->getProjectName());
		$fols = $projectFolderDAO->getFolderByProject($pro);
		if($fols != null) {
			$folderList = null;
			$projectList['leaf'] = false;
			$projectList['expandable'] = true;
			foreach ($fols as $folder) {
				$folderList[] = array('id' => 'f_'.$folder->getFolderPK(), 'text' => $folder->getFolderName(), 'leaf' => false, 'expandable' => false);
			}
			$projectList['root'] = $folderList;
		} else {
			$projectList['leaf'] = false;
			$projectList['expandable'] = false;
		}		
		$data[] = $projectList;
	}
	
	
	echo json_encode(array('root' => $data));
}
?>